package com.macro.mall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.TiTrainingMapper;
import com.macro.mall.mapper.TiTrainingSignRecordLogMapper;
import com.macro.mall.mapper.TiTrainingSignRecordMapper;
import com.macro.mall.mapper.TiTrainingSourseVideoMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.service.TiTrainingSignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TiTrainingSign的服务接口的实现类
 *
 * @author
 */
@Slf4j
@Service
public class TiTrainingSignServiceImpl implements TiTrainingSignService {

    private boolean isDebugEnabled = true;

    @Autowired
    private TiTrainingMapper tiTrainingMapper;
    @Autowired
    private TiTrainingSignRecordMapper tiTrainingSignRecordMapper;
    @Autowired
    private TiTrainingSignRecordLogMapper tiTrainingSignRecordLogMapper;
    @Autowired
    private TiTrainingSourseVideoMapper tiTrainingSourseVideoMapper;

    @Override
    public List<TiTrainingSignRecordLog> find(String courseName,String communityName,String phone,String userIdentity,String signStatus,Integer pageNum,Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        PageHelper.startPage(pageNum, pageSize);
        Assist assist = new Assist();
        List<TiTrainingSignRecordLog> result = null;
        try {
            if (StrUtil.isNotEmpty(courseName)) {
                assist.andLike("course_name", "%" + courseName +"%");
            }
            if (StrUtil.isNotEmpty(communityName)) {
                assist.andLike("community_name", "%" + communityName +"%");
            }
            if (StrUtil.isNotEmpty(phone)) {
                assist.andLike("phone", "%" + phone +"%");
            }
            if (StrUtil.isNotEmpty(userIdentity)) {
                assist.andLike("user_identity", "%" + userIdentity +"%");
            }
            if (StrUtil.isNotEmpty(signStatus)) {
                assist.andEq("sign_status", signStatus);
                if ("01".equals(signStatus)) {
                    assist.orEq("sign_status", "02");
                }
            }else {
                assist.andNeq("sign_status", "null");
            }
            assist.setOrder(Assist.order("create_time",false));
            result = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLog(assist);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取TiTrainingSignRecordLog数据集-->结果:{}", result);
        }
        return result;
    }

    @Override
    public TiTrainingSignRecordLog findOne(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog的id获得TiTraining对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog的id获得TiTraining对象-->失败:id不能为空");
        }
        TiTrainingSignRecordLog result = null;
        try {
            result = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecordLog的id获得TiTraining对象-->结果:{}", result);
        }
        return result;
    }

    @Override
    public CommonResult signConfig(TiTrainingSignRecordLog request,UmsMember a) {
        if (request == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog请求操作数据库-->失败:对象为null");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog请求操作数据库-->失败:对象为null");
        }
        Date currentTime = new Date();
        request.setPhone(a.getPhone());
        TiTrainingSignRecordLog signCheck = null;
        TiTraining tiTraining = null;
        TiTrainingSourseVideo ttsv = null;
        TiTrainingSignRecord ttsr = null;
        int result = 0;
        try {
            switch (request.getOper()){
                case "01":
                    signCheck = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(request);
                    if (!StringUtils.isEmpty(signCheck)&&!StringUtils.isEmpty(signCheck.getSignStatus())) {
                        return CommonResult.failed(ResultCode.VALIDATE_FAILED,"无需重复签到");
                    }
                    tiTraining = tiTrainingMapper.selectTiTrainingById(request.getTrainingId());
                    if (!StringUtils.isEmpty(tiTraining)) {
                        List<TiTrainingSignRecord> srSignInList = tiTraining.getSignList().stream().filter(tts ->
                                tts.getSignInStartTime().before(currentTime) && tts.getSignInEndTime().after(currentTime)
                        ).sorted(Comparator.comparing(TiTrainingSignRecord::getId)).collect(Collectors.toList());
                        //可以簽到
                        if (!CollectionUtils.isEmpty(srSignInList)) {
                            request.setSignRecordId(srSignInList.get(0).getId());
                            ttsv = tiTrainingSourseVideoMapper.selectTiTrainingSourseVideoById(request.getCourseId());
                            if (!StringUtils.isEmpty(ttsv)&&!StringUtils.isEmpty(ttsv.getName())) {
                                request.setCourseName(ttsv.getName());
                            }
                            request.setTrainingName(tiTraining.getName());
                            request.setCommunityId(a.getCommunityId());
                            request.setCommunityName(a.getCommunityName());
                            request.setUserIdentity(a.getUserIdentity());
                            request.setName(a.getName());
                            request.setSignStatus("01");
                            request.setSignInTime(currentTime);
                            if(!StringUtils.isEmpty(signCheck)) {
                                request.setId(signCheck.getId());
                                request.setUpdateTime(currentTime);
                                result = tiTrainingSignRecordLogMapper.updateNotNullTiTrainingSignRecordLogById(request);
                            }else {
                                request.setCreateTime(currentTime);
                                result = tiTrainingSignRecordLogMapper.insertNotNullTiTrainingSignRecordLog(request);
                            }
                        } else {
                            return CommonResult.failed(ResultCode.VALIDATE_FAILED,"不在签到时间区间");
                        }
                    }
                    break;
                case "02":
                    signCheck = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(request);
                    if (!StringUtils.isEmpty(signCheck)&&!StringUtils.isEmpty(signCheck.getSignStatus())) {
                        if ("01".equals(signCheck.getSignStatus())) {
                            //可以簽退
                            ttsr = tiTrainingSignRecordMapper.selectTiTrainingSignRecordById(signCheck.getSignRecordId());
                            if (!StringUtils.isEmpty(ttsr)) {
                                //可以簽退
                                if (ttsr.getSignOutStartTime().before(currentTime) && ttsr.getSignOutEndTime().after(currentTime)) {
                                    request.setId(signCheck.getId());
                                    request.setSignStatus("02");
                                    request.setSignOutTime(currentTime);
                                    request.setUpdateTime(currentTime);
                                    result = tiTrainingSignRecordLogMapper.updateNotNullTiTrainingSignRecordLogById(request);
                                } else {
                                    return CommonResult.failed(ResultCode.VALIDATE_FAILED, "不在签退时间区间");
                                }
                            }
                        } else {
                            return CommonResult.failed(ResultCode.VALIDATE_FAILED, "请勿重复签退");
                        }
                    } else {
                        return CommonResult.failed(ResultCode.VALIDATE_FAILED,"请先签到");
                    }
                    break;
                default:
                    return CommonResult.failed(ResultCode.VALIDATE_FAILED,"01-签到|02-签退");
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("查询TiTrainingSignRecordLog最新一条用户签到签退记录-->结果:{}",signCheck);
            log.debug("通过专题ID查询TiTraining判断签到区间-->结果:{}",tiTraining);
            log.debug("通过TiTrainingSignRecord的id查询TiTrainingSignRecord判断签退区间-->结果:{}",ttsr);
            log.debug("通过课程ID查询TiTrainingSourseVideo获取课程名称签到-->结果:{}",ttsv);
            log.debug("执行通过TiTrainingSignRecordLog请求操作数据库-->结果:{}",result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNull(TiTrainingSignRecordLog value,UmsMember member) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            value.setPhone(member.getPhone());
            TiTrainingSignRecordLog srLog = new TiTrainingSignRecordLog();
            srLog.setTrainingId(value.getTrainingId());
            srLog.setCourseId(value.getCourseId());
            srLog.setPhone(member.getPhone());
            TiTrainingSignRecordLog ttsrl = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(srLog);
            if(StringUtils.isEmpty(ttsrl)) {
                value.setCreateTime(new Date());
                result = tiTrainingSignRecordLogMapper.insertNotNullTiTrainingSignRecordLog(value);
                return CommonResult.success(null);
            }
            value.setId(ttsrl.getId());
            value.setUpdateTime(new Date());
            result = tiTrainingSignRecordLogMapper.updateNotNullTiTrainingSignRecordLogById(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->结果:{}", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult selectOne(TiTrainingSignRecordLog value,UmsMember member) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->失败:对象为null");
        }
        TiTrainingSignRecordLog result = null;
        try {
            value.setPhone(member.getPhone());
            result = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->结果:{}", result);
        }
        return CommonResult.success(result);
    }

}